import os
import re
import pandas as pd
from datetime import datetime

def extract_order_info(msg):
    # 定义需要查找的字段（支持多种可能的字段名称）
    required_fields = {
        "Event Name": r"Event Name:\s*(.+)|Event:\s*(.+)",  # 支持 Event Name 或 Event
        "Quantity": r"Quantity of Tickets:\s*(\d+)|Qty:\s*(\d+)|Quantity:\s*(\d+)",  # 支持多种 Quantity 格式
        # "Email": r"Email Address:\s*([^\s]+)|Email:\s*([^\s]+)|Email\s*([^\s]+)"  # 支持 Email Address 或 Email
    }
    
    # 初始化结果字典
    result = {}
    
    # 检查是否可以提取所有必需字段
    for field, pattern in required_fields.items():
        match = re.search(pattern, msg, re.IGNORECASE)  # 忽略大小写匹配
        if match:
            # 提取第一个非空匹配组
            value = next((group for group in match.groups() if group is not None), None)
            if value:
                # 根据字段类型进行适当转换
                if field == "Quantity":
                    result[field] = int(value.strip())
                else:
                    result[field] = value.strip()
            print(f"Matched {field}: {value}")  # 调试信息
        else:
            print(f"No match for {field}")  # 调试信息
            return None  # 如果某个字段未找到，返回 None
        

            # 对于 Email 字段，使用更广泛的匹配策略
    email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
    emails_found = re.findall(email_pattern, msg)
    if emails_found:
        # 假设最后一个出现的email为订单确认email
        result["Email"] = emails_found[-1]
        print(f"Matched Email: {emails_found[-1]}")
    else:
        print("No match for Email")
        return None
    
    return result


def update_order_hist(order_data):
    """将订单信息写入CSV文件"""
    order_file = "data/order_hist.csv"
    print(f"order_util order_data: {order_data}")

    # 准备订单数据
    new_order = {
        "order_id": int(datetime.now().timestamp()*1000),
        "event_id": order_data["order_data"].get("event_id", ""),
        "user_name": order_data["order_data"].get("user_name", ""),
        "user_email": order_data["order_data"].get("user_email", ""),
        "seat_A": order_data["order_data"].get("seat_class_A", ""),
        "seat_B": order_data["order_data"].get("seat_class_B", ""),
        "seat_C": order_data["order_data"].get("seat_class_C", ""),
        "total_price": order_data["order_data"].get("total_price", 0.0),
        "order_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    }
    print(f"order_util new_order: {new_order}")
    # 如果文件不存在则创建
    if not os.path.exists(order_file):
        print("if")
        df = pd.DataFrame([new_order])
    else:
        df = pd.read_csv(order_file)
        df = pd.concat([df, pd.DataFrame([new_order])], ignore_index=True)
    
    df.to_csv(order_file, index=False)